package com.alex.service;

import com.alex.dao.BookMapper;
import com.alex.dao.BookStockMapper;
import com.alex.pojo.Book;
import com.alex.pojo.BookStock;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service("bookService")
@Transactional
public class BookServiceImpl implements BookService {

    @Resource
    private BookMapper bookMapper;

    @Resource
    private BookStockMapper bookStockMapper;

    @Override
    public boolean add(Book book) {
        return bookMapper.add(book)==1;
    }

    @Override
    public boolean delete(String isbn) {
        return bookMapper.delete(isbn)==1;
    }

    @Override
    public boolean update(Book book) {
        int r1 = bookMapper.update(book);
        int r2 = bookStockMapper.updateStock(book.getIsbn(), book.getStock());
        return r1==1 && r2==1;
    }

    @Override
    public Book get(String isbn) {
        return bookMapper.get(isbn);
    }

    @Override
    public List<Book> getAll() {
        return bookMapper.getAll();
    }

    @Override
    public List<Book> searchByName(String keyword) {
        return bookMapper.query(keyword);
    }

    @Override
    public boolean buyOneBook(String isbn, String username) {
        BookStock bookStock = bookStockMapper.get(isbn);
        if (bookStock.getStock() < 1) {
            return false;
        }

        return bookStockMapper.updateStock(isbn, bookStock.getStock()-1) == 1;
    }
}
